package in.hbb20.countrycodepickerproject.fragment;

import ohos.aafwk.content.Intent;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;

import java.util.List;

public class FragmentPageAdapter extends PageSliderProvider implements PageSlider.PageChangedListener {

    private List<Fragment> fragmentList;

    private int mCurrentPage = 0;

    public FragmentPageAdapter(List<Fragment> fragmentList) {
        this.fragmentList = fragmentList;
    }

    @Override
    public int getCount() {
        return fragmentList != null ? fragmentList.size() : 0;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Fragment iFragment = fragmentList.get(i);
        return iFragment.attachToContainer(componentContainer);
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent((Component) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return component == o;
    }

    @Override
    public void onPageSliding(int i, float v, int i1) {

    }

    @Override
    public void onPageSlideStateChanged(int i) {

    }

    @Override
    public void onPageChosen(int i) {
        if (fragmentList != null && !fragmentList.isEmpty()) {
            onBackground();
        }
        this.mCurrentPage = i;
        if (fragmentList != null && !fragmentList.isEmpty()) {
            onForeground(null);
        }
    }

    public void onForeground(Intent intent) {
        if (fragmentList != null && !fragmentList.isEmpty()) {
            Fragment iFragment = fragmentList.get(mCurrentPage);
            iFragment.onForeground(intent);
        }
    }

    public void onBackground() {
        if (fragmentList != null && !fragmentList.isEmpty()) {
            Fragment iFragment = fragmentList.get(mCurrentPage);
            iFragment.onBackground();
        }
    }
}
